﻿Imports BusinessLayer
Imports CommonLayer
Imports System.Security.Cryptography
Imports Infragistics.Win.UltraWinGrid
Imports Infragistics.Win
Imports System.Text
Imports System.Collections.Generic

Public Class CommonFunction
    Public Const DateFormatString As String = "dd/MM/yyyy"
    Public Const mscSQLExceptionContrainsNumber As Integer = 547
    Public Const mscSortOrder As String = "SortOrder"
    Public Const mscBuildApplication As Boolean = True
    Public Const mscDemoBuildApplication As Boolean = True

    Public Shared MySession As ApplicationSession = Nothing
    Public Shared oBLSecurity As BLSecurity

    Public Shared Function ShowQuestionMessage(ByVal message As String, ByVal eButton As MessageBoxButtons) _
        As DialogResult
        Return MessageBox.Show(message, Application.ProductName, eButton, MessageBoxIcon.Question)
    End Function

    Public Shared Sub ShowInfoMessage(ByVal message As String)
        MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Public Shared Sub ShowExclamation(ByVal message As String)
        MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End Sub

    Public Shared Sub ShowExceptionMessage(ByVal ex As Exception)
        MessageBox.Show(ex.ToString, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End Sub


    Public Shared Function RefineTitleText(ByVal str As String) As String
        Return str.Replace("(*)", "").Trim
    End Function

    ''' <summary>
    ''' Add Row Count 
    ''' </summary>
    ''' <param name="grdControl"></param>
    ''' <param name="strcol"></param>
    ''' <param name="summaryPosition"></param>
    ''' <remarks></remarks>
    Public Shared Sub AddRowCountToGrid(ByRef grdControl As UltraGrid, Optional ByVal strCol As String = "", _
                                        Optional ByVal summaryPosition As SummaryPosition = _
                                           SummaryPosition.UseSummaryPositionColumn)
        With grdControl.DisplayLayout.Bands(0)
            If .GetFirstVisibleCol(grdControl.DisplayLayout.ColScrollRegions(0), False) IsNot Nothing Then
                Dim colLeftKey As String = String.Empty
                If strCol.Trim <> String.Empty Then
                    colLeftKey = strCol
                Else
                    colLeftKey = .GetFirstVisibleCol(grdControl.DisplayLayout.ColScrollRegions(0), False).Key
                End If
                Dim oSummary As SummarySettings
                Dim bExistRowcount As Boolean = False

                For i = 0 To grdControl.DisplayLayout.Bands(0).Summaries.Count - 1
                    oSummary = grdControl.DisplayLayout.Bands(0).Summaries(i)
                    If oSummary.SummaryType = SummaryType.Count Then
                        oSummary.DisplayFormat = My.Resources.mscRowCountTitle
                        oSummary.Appearance.TextHAlign = HAlign.Left
                        oSummary.SummaryPosition = summaryPosition.UseSummaryPositionColumn
                        oSummary.SourceColumn = .Columns(colLeftKey)
                        oSummary.SummaryPositionColumn = .Columns(colLeftKey)
                        bExistRowcount = True
                    End If
                Next

                If Not bExistRowcount Then
                    If .Columns.Count > 0 AndAlso Not .Summaries.Exists(My.Resources.mscRowCountSummaryKey) Then
                        .Summaries.Add(My.Resources.mscRowCountSummaryKey, SummaryType.Count, .Columns(0), _
                                       summaryPosition)
                        .Summaries(My.Resources.mscRowCountSummaryKey).SourceColumn = .Columns(colLeftKey)
                        .Summaries(My.Resources.mscRowCountSummaryKey).SummaryPositionColumn = .Columns(colLeftKey)
                        .Summaries(My.Resources.mscRowCountSummaryKey).DisplayFormat = My.Resources.mscRowCountTitle
                        .Summaries(My.Resources.mscRowCountSummaryKey).Appearance.TextHAlign = HAlign.Left
                    End If
                End If
            End If

            .Override.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed + SummaryDisplayAreas.GroupByRowsFooter
            .Override.SummaryFooterCaptionVisible = DefaultableBoolean.False
        End With
    End Sub

    ''' <summary>
    ''' Add Summary To Column
    ''' </summary>
    ''' <param name="grdControl"></param>
    ''' <param name="strCol"></param>
    ''' <param name="strFormat"></param>
    ''' <remarks></remarks>
    Public Shared Sub AddSummaryToColumn(ByVal grdControl As UltraGrid, ByVal strCol As String, _
                                         ByVal strFormat As String)
        If grdControl IsNot Nothing AndAlso grdControl.DisplayLayout.Bands.Count > 0 Then
            With grdControl.DisplayLayout.Bands(0)
                If grdControl.DisplayLayout.Bands(0).Columns.Exists(strCol.Trim) Then
                    Dim strSumKey As String = "Sum" & strCol
                    Dim sumSetting As SummarySettings = Nothing

                    For i = 0 To .Summaries.Count - 1
                        If .Summaries(i).SourceColumn.Key = strCol AndAlso .Summaries(i).SummaryType <> SummaryType.Count Then
                            sumSetting = .Summaries(i)
                            Exit For
                        End If
                    Next

                    If sumSetting IsNot Nothing Then
                        .Summaries.Remove(sumSetting)
                        sumSetting = Nothing
                    End If
                    sumSetting = .Summaries.Add(strSumKey, SummaryType.Sum)
                    sumSetting.Key = strSumKey
                    sumSetting.SummaryType = SummaryType.Sum
                    sumSetting.Appearance.TextHAlign = HAlign.Right
                    sumSetting.DisplayFormat = "{0:" & strFormat & "}"
                    sumSetting.SourceColumn = .Columns(strCol)
                    sumSetting.SummaryDisplayArea = SummaryDisplayAreas.BottomFixed
                    sumSetting.SummaryPosition = SummaryPosition.UseSummaryPositionColumn
                    sumSetting.SummaryPositionColumn = sumSetting.SourceColumn
                End If
            End With
        End If
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="combo"></param>
    ''' <remarks></remarks>
    Public Shared Sub RefineCombo(ByVal combo As UltraDropDownBase)
        Try
            With combo.DisplayLayout.Override
                .BorderStyleRow = UIElementBorderStyle.None
                .BorderStyleCell = UIElementBorderStyle.None
                .BorderStyleHeader = UIElementBorderStyle.None
                .HeaderStyle = HeaderStyle.Standard
                .HeaderAppearance.BackColor = Office2007ColorTable.Colors.RibbonGroupButtonGradientDark
                .HeaderAppearance.BackColor = Office2007ColorTable.Colors.RibbonGroupButtonGradientLight
                .HeaderAppearance.BackGradientStyle = GradientStyle.GlassTop37Bright
                .HotTrackRowAppearance.BackColor = SystemColors.Highlight
                .HotTrackRowAppearance.ForeColor = SystemColors.HighlightText
                .TipStyleCell = TipStyle.Show
                'added by tqnga 08/12/2008
                .MinRowHeight = 20
            End With
            combo.DisplayLayout.NewColumnLoadStyle = NewColumnLoadStyle.Hide
            'add by tnson 03/07/08
        Catch ex As Exception

        End Try
    End Sub

    Public Shared Function GetCurrentRow(ByVal oBindingSource As BindingSource) As DataRow
        Dim row As DataRow = Nothing
        If oBindingSource IsNot Nothing Then
            If Not IsNothing(oBindingSource.Current) Then
                row = CType(oBindingSource.Current, DataRowView).Row
            End If
        End If
        Return row
    End Function

    Public Shared Sub SetFilterNotEqualID(ByVal stringID As String(), ByVal bsList As BindingSource, _
                                          ByVal strIDField As String)
        If stringID IsNot Nothing AndAlso stringID.Length > 0 Then
            Dim sbList As StringBuilder = New StringBuilder

            For i As Integer = 0 To stringID.Length - 1
                If i > 0 Then
                    sbList.Append(",'" + stringID(i) + "'")
                Else
                    sbList.Append("'" + stringID(i) + "'")
                End If
            Next

            bsList.Filter = strIDField + " NOT IN(" + sbList.ToString + ")"
        End If
    End Sub

    Public Shared Function GetDataRow(ByVal row As UltraGridRow) As DataRow
        If row.IsDataRow Then
            Return CType(row.ListObject, DataRowView).Row
        End If
        Return Nothing
    End Function

    Public Shared Function GetDataRow(ByVal row As DataRowView) As DataRow
        Return row.Row
    End Function

    Public Shared Sub GenerateAccountingTypeData( _
                                                 ByRef dtAccoutingObjectType As  _
                                                    DataSetLocal.AccountingObjectTypeSourceDataTable)
        If dtAccoutingObjectType Is Nothing Then
            dtAccoutingObjectType = New DataSetLocal.AccountingObjectTypeSourceDataTable
        Else
            dtAccoutingObjectType.Clear()
        End If
        'dsLocal.AccountingObjectTypeSource.Clear()
        Dim dr As DataSetLocal.AccountingObjectTypeSourceRow = Nothing

        dr = dtAccoutingObjectType.NewAccountingObjectTypeSourceRow

        With dr
            .AccountingObjectType = AccountingObjectType.Customer
            .Description = "Khách hàng"
        End With

        dtAccoutingObjectType.AddAccountingObjectTypeSourceRow(dr)

        dr = dtAccoutingObjectType.NewAccountingObjectTypeSourceRow

        With dr
            .AccountingObjectType = AccountingObjectType.Vendor
            .Description = "Nhà cung cấp"
        End With

        dtAccoutingObjectType.AddAccountingObjectTypeSourceRow(dr)

        dr = dtAccoutingObjectType.NewAccountingObjectTypeSourceRow

        With dr
            .AccountingObjectType = AccountingObjectType.Both
            .Description = "Khách hàng - Nhà cung cấp"
        End With

        dtAccoutingObjectType.AddAccountingObjectTypeSourceRow(dr)

        dtAccoutingObjectType.AcceptChanges()
    End Sub

    ''' <summary>
    ''' Kiem tra xem co can Load lai du lieu Detail khong
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function CheckForLoadDetailData(ByVal masterID As String, ByVal dtDetail As DataTable, _
                                                  ByVal sForeignKey As String) As Boolean
        Dim bResult As Boolean = False

        If dtDetail IsNot Nothing AndAlso dtDetail.Columns.Contains(sForeignKey) Then

        End If

        Return bResult
    End Function

    Public Shared Function GetOpeningDate() As Date
        Return DateSerial(Today.Year - 1, 12, 31)
    End Function

    Public Shared Function EncryptMD5(ByVal stringData As String) As String
        Dim md5Hasher As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
        Dim hashedDataBytes As Byte() = Nothing
        Dim oEncoder As UTF8Encoding = New UTF8Encoding

        hashedDataBytes = md5Hasher.ComputeHash(oEncoder.GetBytes(stringData))

        Return Convert.ToBase64String(hashedDataBytes)
    End Function

    'Public Shared Sub SetFormatForControl(ByVal oDisplayInfo As DevExpress.Utils.FormatInfo, ByVal oMaskInfo As Mask.MaskProperties, ByVal eDataType As Entity.DataFormatEnum)
    '    Select Case eDataType
    '        Case Entity.DataFormatEnum.CurrencyType
    '            If oMaskInfo IsNot Nothing Then
    '                With oMaskInfo
    '                    .MaskType = Mask.MaskType.Numeric
    '                    .UseMaskAsDisplayFormat = True
    '                    .EditMask = "N" & MySession.NumberFormat.CurrencyDecimalDigits
    '                End With
    '            Else
    '                If oDisplayInfo IsNot Nothing Then
    '                    With oDisplayInfo
    '                        .FormatType = DevExpress.Utils.FormatType.Numeric
    '                        .FormatString = "N" & MySession.NumberFormat.CurrencyDecimalDigits
    '                    End With
    '                End If
    '            End If
    '        Case Entity.DataFormatEnum.DateTimeType
    '            If oMaskInfo IsNot Nothing Then
    '                With oMaskInfo
    '                    .MaskType = Mask.MaskType.DateTime
    '                    .UseMaskAsDisplayFormat = True
    '                    .EditMask = "dd/MM/yyyy"
    '                End With
    '            Else
    '                If oDisplayInfo IsNot Nothing Then
    '                    With oDisplayInfo
    '                        .FormatType = DevExpress.Utils.FormatType.DateTime
    '                        .FormatString = "dd/MM/yyyy"
    '                    End With
    '                End If
    '            End If
    '        Case Entity.DataFormatEnum.DecimalType
    '            If oMaskInfo IsNot Nothing Then
    '                With oMaskInfo
    '                    .MaskType = Mask.MaskType.Numeric
    '                    .UseMaskAsDisplayFormat = True
    '                    .EditMask = "N" & MySession.NumberFormat.NumberDecimalDigits
    '                End With
    '            Else
    '                If oDisplayInfo IsNot Nothing Then
    '                    With oDisplayInfo
    '                        .FormatType = DevExpress.Utils.FormatType.Numeric
    '                        .FormatString = "N" & MySession.NumberFormat.NumberDecimalDigits
    '                    End With
    '                End If
    '            End If
    '        Case Entity.DataFormatEnum.IntegerType
    '            If oMaskInfo IsNot Nothing Then
    '                With oMaskInfo
    '                    .MaskType = Mask.MaskType.Numeric
    '                    .UseMaskAsDisplayFormat = True
    '                    .EditMask = "N0"
    '                End With
    '            Else
    '                If oDisplayInfo IsNot Nothing Then
    '                    With oDisplayInfo
    '                        .FormatType = DevExpress.Utils.FormatType.Numeric
    '                        .FormatString = "N0"
    '                    End With
    '                End If
    '            End If
    '    End Select
    'End Sub


    Public Shared Function CheckPermissionByID(ByVal sUserID As String, ByVal ePermission As PermissionEnum, _
                                               ByVal eAction As ActionEnum) As Boolean
        'Dim bResult As Boolean = False

        'If mscBuildApplication AndAlso MySession IsNot Nothing AndAlso MySession.IsLogIn Then
        '    If oBLSecurity Is Nothing Then
        '        oBLSecurity = New BusinessLayer.BLSecurity
        '    End If

        '    bResult = oBLSecurity.CheckPermissionByActor(sUserID, CInt(ePermission), CInt(eAction))
        '    If Not bResult Then
        '        ShowExclamation("Bạn không có quyền thực hiện chức năng này.")
        '    End If
        'Else
        '    bResult = True
        'End If


        'Return bResult
        Return True
    End Function
End Class
